<!DOCTYPE html>

<html>
<head>
  <title>blockchain.js</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="arkio.css" />
</head>
<body>
  
    <div id="title">
         <h1>blockchain.js</h1>
         <img src="https://ark.io/wp-content/uploads/2016/10/ark-normal.png">
        <hr>
    </div>
  
  <div id="container">
    <div id="background"></div>
    
      <ul id="jump_to">
        <li>
          <a class="large" href="javascript:void(0);">Jump To &hellip;</a>
          <a class="small" href="javascript:void(0);">+</a>
          <div id="jump_wrapper">
          <div id="jump_page_wrapper">
            <div id="jump_page">
              
                
                <a class="source" href="README.html">
                  README.md
                </a>
              
                
                <a class="source" href="app.html">
                  app.js
                </a>
              
                
                <a class="source" href="accounts.html">
                  accounts.js
                </a>
              
                
                <a class="source" href="blockchain.html">
                  blockchain.js
                </a>
              
                
                <a class="source" href="blocks.html">
                  blocks.js
                </a>
              
                
                <a class="source" href="delegates.html">
                  delegates.js
                </a>
              
                
                <a class="source" href="loader.html">
                  loader.js
                </a>
              
                
                <a class="source" href="multisignatures.html">
                  multisignatures.js
                </a>
              
                
                <a class="source" href="nodeManager.html">
                  nodeManager.js
                </a>
              
                
                <a class="source" href="peers.html">
                  peers.js
                </a>
              
                
                <a class="source" href="rounds.html">
                  rounds.js
                </a>
              
                
                <a class="source" href="server.html">
                  server.js
                </a>
              
                
                <a class="source" href="signatures.html">
                  signatures.js
                </a>
              
                
                <a class="source" href="system.html">
                  system.js
                </a>
              
                
                <a class="source" href="transactionPool.html">
                  transactionPool.js
                </a>
              
                
                <a class="source" href="transactions.html">
                  transactions.js
                </a>
              
                
                <a class="source" href="transport.html">
                  transport.js
                </a>
              
            </div>
          </div>
        </li>
      </ul>
    
    <ul class="sections">
        
        
        <li id="section-1">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-1">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">var</span> <span class="hljs-keyword">async</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async'</span>);
<span class="hljs-keyword">var</span> constants = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../helpers/constants.js'</span>);
<span class="hljs-keyword">var</span> slots = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../helpers/slots.js'</span>);

<span class="hljs-keyword">var</span> self, library, modules;

<span class="hljs-keyword">var</span> __private = {</pre></div></div>
            
        </li>
        
        
        <li id="section-2">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-2">&#182;</a>
              </div>
              <p>Estimation of clock drift from network in seconds</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	clockdrift: <span class="hljs-number">0</span>,</pre></div></div>
            
        </li>
        
        
        <li id="section-3">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-3">&#182;</a>
              </div>
              <p>Indexed by height</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	blockchain: {},</pre></div></div>
            
        </li>
        
        
        <li id="section-4">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-4">&#182;</a>
              </div>
              <p>Indexed by height all blocks considered as orphaned</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	orphanedBlocks: {},</pre></div></div>
            
        </li>
        
        
        <li id="section-5">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-5">&#182;</a>
              </div>
              <p>List of blocks received higher than lastBlock.height that can’t be processed
Indicator of being forked from network
To use carefully as it can be a vector of attack
Indexed by height</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	forkedChainBlocks: {},</pre></div></div>
            
        </li>
        
        
        <li id="section-6">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-6">&#182;</a>
              </div>
              <p>Last block processed in the blockchain</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	lastBlock: {<span class="hljs-attr">height</span>: <span class="hljs-number">0</span>}
};</pre></div></div>
            
        </li>
        
        
        <li id="section-7">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-7">&#182;</a>
              </div>
              <p>Constructor</p>

            </div>
            
            <div class="content"><div class='highlight'><pre><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Blockchain</span> (<span class="hljs-params">cb, scope</span>) </span>{
	library = scope;
	self = <span class="hljs-keyword">this</span>;
	setImmediate(cb, <span class="hljs-literal">null</span>, self);
}</pre></div></div>
            
        </li>
        
        
        <li id="section-8">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-8">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBind</code></p>

            </div>
            
        </li>
        
        
        <li id="section-9">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-9">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBind = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">scope</span>) </span>{
	modules = scope;
};</pre></div></div>
            
        </li>
        
        
        <li id="section-10">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-10">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onStartBlockchain</code></p>

            </div>
            
        </li>
        
        
        <li id="section-11">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-11">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onStartBlockchain = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
	setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listenBlockchainState</span>(<span class="hljs-params"></span>)</span>{
		<span class="hljs-keyword">var</span> state = __private.timestampState();
		<span class="hljs-keyword">if</span>(state.rebuild){
			<span class="hljs-keyword">var</span> timedout=<span class="hljs-literal">false</span>;
			library.logger.warn(<span class="hljs-string">"Blockchain rebuild triggered"</span>, state);
			library.bus.message(<span class="hljs-string">"rebuildBlockchain"</span>, <span class="hljs-number">3</span>, state, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err,block</span>)</span>{</pre></div></div>
            
        </li>
        
        
        <li id="section-12">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-12">&#182;</a>
              </div>
              <p>rebuild done</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>				<span class="hljs-keyword">if</span>(block){
					__private.timestampState(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
					library.logger.warn(<span class="hljs-string">"Blockchain rebuild done"</span>, __private.timestampState());
					<span class="hljs-keyword">if</span>(!timedout){
						timedout=<span class="hljs-literal">true</span>;
						setTimeout(listenBlockchainState, <span class="hljs-number">1000</span>);
					}
				}</pre></div></div>
            
        </li>
        
        
        <li id="section-13">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-13">&#182;</a>
              </div>
              <p>rebuild not done because in sync with network (ie network stale)</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>				<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(!err){
					library.logger.warn(<span class="hljs-string">"Rebuild aborted: In sync with observed network"</span>, __private.timestampState());
					library.logger.warn(<span class="hljs-string">"# Network looks stopped"</span>);
					<span class="hljs-keyword">if</span>(!timedout){
						timedout=<span class="hljs-literal">true</span>;
						setTimeout(listenBlockchainState, <span class="hljs-number">10000</span>);
					}
				}</pre></div></div>
            
        </li>
        
        
        <li id="section-14">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-14">&#182;</a>
              </div>
              <p>rebuild not done because of internal error</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>				<span class="hljs-keyword">else</span>{
					library.logger.error(<span class="hljs-string">"Error rebuilding blockchain. You need to restart the node to get in sync"</span>, __private.timestampState());
					<span class="hljs-keyword">if</span>(!timedout){
						timedout=<span class="hljs-literal">true</span>;
						setTimeout(listenBlockchainState, <span class="hljs-number">10000</span>);
					}
				}
			});
		}
		<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(state.stale){
			library.logger.debug(<span class="hljs-string">"Blockchain state"</span>, state);

			library.bus.message(<span class="hljs-string">"downloadBlocks"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, lastblock</span>)</span>{</pre></div></div>
            
        </li>
        
        
        <li id="section-15">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-15">&#182;</a>
              </div>
              <p>TODO: see how the download went for further action</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>			});</pre></div></div>
            
        </li>
        
        
        <li id="section-16">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-16">&#182;</a>
              </div>
              <p>ok let’s try in one more blocktime if still stale</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>			setTimeout(listenBlockchainState, <span class="hljs-number">8000</span>);
		}
		<span class="hljs-keyword">else</span>{
			setTimeout(listenBlockchainState, <span class="hljs-number">1000</span>);
		}
	});

	setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cleanBlockchain</span>(<span class="hljs-params"></span>)</span>{
		<span class="hljs-keyword">var</span> height = __private.lastBlock.height;
		<span class="hljs-keyword">var</span> blockremoved = __private.blockchain[height<span class="hljs-number">-200</span>];
		library.logger.debug(<span class="hljs-string">"Removing from memory blockchain blocks with height under"</span>, height<span class="hljs-number">-200</span>);
		<span class="hljs-keyword">while</span>(blockremoved){
			<span class="hljs-keyword">delete</span> __private.blockchain[blockremoved.height];
			blockremoved = __private.blockchain[<span class="hljs-string">""</span>+(blockremoved.height<span class="hljs-number">-1</span>)];
		}
		setTimeout(cleanBlockchain, <span class="hljs-number">10000</span>);
	});
}</pre></div></div>
            
        </li>
        
        
        <li id="section-17">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-17">&#182;</a>
              </div>
              <p><strong>API</strong> <code>upsertBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-18">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-18">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.upsertBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, cb</span>)</span>{
  <span class="hljs-keyword">var</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">if</span>(!__private.blockchain[block.height]){
    __private.blockchain[block.height]=block;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(__private.blockchain[block.height].id!=block.id){
		__private.orphanedBlocks[block.id]=block;
    error = <span class="hljs-string">"upsertBlock - Orphaned Block has been added in the blockchain"</span>;
  } <span class="hljs-keyword">else</span> {
    __private.blockchain[block.height]=block;
  }
  <span class="hljs-keyword">return</span> cb &amp;&amp; setImmediate(cb, error, __private.blockchain[block.height]);
}</pre></div></div>
            
        </li>
        
        
        <li id="section-19">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-19">&#182;</a>
              </div>
              <p><strong>API</strong> <code>isOrphaned</code></p>

            </div>
            
        </li>
        
        
        <li id="section-20">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-20">&#182;</a>
              </div>
              <p>Check if the block is orphaned, ie if the blockchain has already received another (different id) block at same height
It also check for double forgery (different id, same timestamp, same height and same generatorPublicKey)</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.isOrphaned = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>)</span>{
	<span class="hljs-keyword">if</span>(__private.blockchain[block.height] &amp;&amp; __private.blockchain[block.height].id != block.id){
		<span class="hljs-keyword">if</span>(__private.blockchain[block.height] &amp;&amp; __private.blockchain[block.height].generatorPublicKey == block.generatorPublicKey &amp;&amp; __private.blockchain[block.height].timestamp == block.timestamp){
			modules.accounts.getAccount({<span class="hljs-attr">publicKey</span>:block.generatorPublicKey}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, delegate</span>)</span>{
				library.logger.warn(<span class="hljs-string">"Double forgery"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">generator</span>:block.generatorPublicKey, <span class="hljs-attr">username</span>: delegate.username, <span class="hljs-attr">height</span>:block.height});
			});
		}
		<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
	}
	<span class="hljs-keyword">else</span> {
		<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
	}
}</pre></div></div>
            
        </li>
        
        
        <li id="section-21">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-21">&#182;</a>
              </div>
              <p><strong>API</strong> <code>isForked</code></p>

            </div>
            
        </li>
        
        
        <li id="section-22">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-22">&#182;</a>
              </div>
              <p>Get a block but can’t find the previousBlock in the blockchain</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.isForked = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>)</span>{
	<span class="hljs-keyword">var</span> previousBlock = __private.blockchain[<span class="hljs-string">""</span>+(block.height<span class="hljs-number">-1</span>)];
	<span class="hljs-keyword">return</span> previousBlock &amp;&amp; previousBlock.id != block.previousBlock;
}</pre></div></div>
            
        </li>
        
        
        <li id="section-23">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-23">&#182;</a>
              </div>
              <p><strong>API</strong> <code>isPresent</code></p>

            </div>
            
        </li>
        
        
        <li id="section-24">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-24">&#182;</a>
              </div>
              <p>Check if block is already in blockchain (ie same id) or already found as orphaned</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.isPresent = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>)</span>{

	<span class="hljs-keyword">return</span> (__private.blockchain[block.height] &amp;&amp; __private.blockchain[block.height].id == block.id) || __private.orphanedBlocks[block.id];
}</pre></div></div>
            
        </li>
        
        
        <li id="section-25">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-25">&#182;</a>
              </div>
              <p><strong>API</strong> <code>isReady</code></p>

            </div>
            
        </li>
        
        
        <li id="section-26">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-26">&#182;</a>
              </div>
              <p>Check if the blockchain is ready to receive the block (ie received the block at height - 1)</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.isReady = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>)</span>{
	<span class="hljs-keyword">var</span> ready = __private.lastBlock.height == block.height - <span class="hljs-number">1</span>;
	<span class="hljs-keyword">if</span>(ready){
		<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
	}
	<span class="hljs-keyword">else</span>{
		__private.forkedChainBlocks[block.height]=block;
		<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
	}
}</pre></div></div>
            
        </li>
        
        
        <li id="section-27">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-27">&#182;</a>
              </div>
              <p><strong>API</strong> <code>addBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-28">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-28">&#182;</a>
              </div>
              <p>Setter the block to the blockchain model, raise error if there is already another one at same height
Does not check if this is coherent with blockchain (ie previousBlock)</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.addBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, cb</span>)</span>{
  <span class="hljs-keyword">var</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">if</span>(!__private.blockchain[block.height]){
    __private.blockchain[block.height]=block;
  }
  <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(__private.blockchain[block.height].id != block.id){
		__private.orphanedBlocks[block.id]=block;
    error = <span class="hljs-string">"addBlock - Orphaned Block has been added in the blockchain"</span>;
  }</pre></div></div>
            
        </li>
        
        
        <li id="section-29">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-29">&#182;</a>
              </div>
              <p>if same block id don’t update</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>  <span class="hljs-keyword">return</span> cb &amp;&amp; setImmediate(cb, error, __private.blockchain[block.height]);
};</pre></div></div>
            
        </li>
        
        
        <li id="section-30">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-30">&#182;</a>
              </div>
              <p>return the previousBlock even if orphaned.
return null if no previous Block found. Likely a fork.</p>
<p><strong>API</strong> <code>getPreviousBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-31">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-31">&#182;</a>
              </div>
              <p>get the previous block from the input block, as stored in memory.
if not found does not check for database, returns undefined.</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.getPreviousBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>)</span>{
	<span class="hljs-keyword">var</span> previousBlock = __private.blockchain[<span class="hljs-string">""</span>+(block.height - <span class="hljs-number">1</span>)];</pre></div></div>
            
        </li>
        
        
        <li id="section-32">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-32">&#182;</a>
              </div>
              <p>useful when there is orphaned block
if(!previousBlock || previousBlock.id !== block.previousBlock){
    previousBlock = __private.orphanedBlocks[block.previousBlock];
}</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>	<span class="hljs-keyword">return</span> previousBlock;
}</pre></div></div>
            
        </li>
        
        
        <li id="section-33">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-33">&#182;</a>
              </div>
              <p><strong>API</strong> <code>removeBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-34">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-34">&#182;</a>
              </div>
              <p>remove block from blockchain in-memory model
raise error if not present, or trying to remove a different block at same height</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.removeBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, cb</span>)</span>{
  <span class="hljs-keyword">var</span> error = <span class="hljs-literal">null</span>;
  <span class="hljs-keyword">if</span>(!__private.blockchain[block.height]){
    error = <span class="hljs-string">"removeBlock - Block already removed from blockchain"</span>
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(__private.blockchain[block.height].id!=block.id){
    error = <span class="hljs-string">"removeBlock - Block has been replaced in the blockchain"</span>;
  } <span class="hljs-keyword">else</span> {
		<span class="hljs-keyword">if</span>(__private.lastBlock.id == __private.blockchain[block.height].id){
			__private.lastBlock = __private.blockchain[<span class="hljs-string">""</span>+(block.height<span class="hljs-number">-1</span>)];
		}
    <span class="hljs-keyword">delete</span> __private.blockchain[block.height];</pre></div></div>
            
        </li>
        
        
        <li id="section-35">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-35">&#182;</a>
              </div>
              <p>TODO: reuse orphaned blocks sending a message to stop rebuild
if one of the orphaned block is at the origin (ie block.previousBlock == orphanedBlock.previousBlock)</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>		<span class="hljs-keyword">delete</span> __private.orphanedBlocks[block.id];
  }
  <span class="hljs-keyword">return</span> cb &amp;&amp; setImmediate(cb, error, block);
};</pre></div></div>
            
        </li>
        
        
        <li id="section-36">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-36">&#182;</a>
              </div>
              <p><strong>API</strong> <code>getBlockAtHeight</code></p>

            </div>
            
        </li>
        
        
        <li id="section-37">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-37">&#182;</a>
              </div>
              <p>Getter from in-memory model, can return undefined</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.getBlockAtHeight = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">height</span>)</span>{
  <span class="hljs-keyword">return</span> __private.blockchain[height];
};</pre></div></div>
            
        </li>
        
        
        <li id="section-38">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-38">&#182;</a>
              </div>
              <p><strong>API</strong> <code>getLastBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-39">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-39">&#182;</a>
              </div>
              <p>return last block on top of the blockchain. Fast access
The block returned is the last one that has been completely processed</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.getLastBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">return</span> __private.lastBlock;
};</pre></div></div>
            
        </li>
        
        
        <li id="section-40">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-40">&#182;</a>
              </div>
              <p>should we have received a new block by now?
fast</p>
<p><strong>API</strong> <code>isMissingNewBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-41">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-41">&#182;</a>
              </div>
              <p>return true if there is no new block from lastBlock for over a blocktime</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.isMissingNewBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
	<span class="hljs-keyword">if</span>(!__private.lastBlock){
		<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
	}
	<span class="hljs-keyword">else</span> {
		<span class="hljs-keyword">return</span> slots.getTime() - __private.lastBlock.timestamp &gt; constants.blocktime;
	}

};</pre></div></div>
            
        </li>
        
        
        <li id="section-42">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-42">&#182;</a>
              </div>
              <p><strong>API</strong> <code>getLastVerifiedBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-43">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-43">&#182;</a>
              </div>
              <p>return last verified block (it may still be rejected during the process)
expensive computation checking the whole in memory blockchain for the highest height and verified</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.getLastVerifiedBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">var</span> lastBlock=<span class="hljs-literal">null</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> height <span class="hljs-keyword">in</span> __private.blockchain){
    <span class="hljs-keyword">if</span>(!lastBlock){
      lastBlock = __private.blockchain[height];
    }
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(<span class="hljs-built_in">parseInt</span>(height)&gt;lastBlock.height &amp;&amp; __private.blockchain[height].verified){
      lastBlock = __private.blockchain[height];
    }
  }
  <span class="hljs-keyword">return</span> lastBlock;
};</pre></div></div>
            
        </li>
        
        
        <li id="section-44">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-44">&#182;</a>
              </div>
              <p><strong>API</strong> <code>getLastIncludedBlock</code></p>

            </div>
            
        </li>
        
        
        <li id="section-45">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-45">&#182;</a>
              </div>
              <p>expensive computation checking the whole in memory blockchain for the highest height
no check is done if it has been verified of processed</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.getLastIncludedBlock = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">var</span> lastBlock=<span class="hljs-literal">null</span>;
  <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> height <span class="hljs-keyword">in</span> __private.blockchain){
    <span class="hljs-keyword">if</span>(!lastBlock){
      lastBlock = __private.blockchain[height];
    }
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(<span class="hljs-built_in">parseInt</span>(height)&gt;lastBlock.height){
      lastBlock = __private.blockchain[height];
    }
  }
  <span class="hljs-keyword">return</span> lastBlock;
};</pre></div></div>
            
        </li>
        
        
        <li id="section-46">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-46">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onDatabaseLoaded</code></p>

            </div>
            
        </li>
        
        
        <li id="section-47">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-47">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onDatabaseLoaded = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">lastBlock</span>) </span>{
	lastBlock.processed = <span class="hljs-literal">true</span>;
	lastBlock.verified = <span class="hljs-literal">true</span>;
	self.upsertBlock(lastBlock);
	__private.timestampState(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
	__private.lastBlock = lastBlock;
};</pre></div></div>
            
        </li>
        
        
        <li id="section-48">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-48">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBlockRemoved</code></p>

            </div>
            
        </li>
        
        
        <li id="section-49">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-49">&#182;</a>
              </div>
              
            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBlockRemoved = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>) </span>{
	<span class="hljs-keyword">return</span> self.removeBlock(block);
}</pre></div></div>
            
        </li>
        
        
        <li id="section-50">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-50">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBlockReceived</code></p>

            </div>
            
        </li>
        
        
        <li id="section-51">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-51">&#182;</a>
              </div>
              <p>Check against in-memory blockchain if the block is ok to be included
If so, mark the block with block.ready=true</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBlockReceived = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, peer</span>) </span>{
	<span class="hljs-keyword">if</span>(self.isPresent(block)){
		library.logger.debug(<span class="hljs-string">"Block already received"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">height</span>:block.height, <span class="hljs-attr">peer</span>:peer.string});
		<span class="hljs-keyword">return</span>;
	}

	<span class="hljs-keyword">if</span>(self.isOrphaned(block)){
		__private.orphanedBlocks[block.id]=block;
		block.orphaned=<span class="hljs-literal">true</span>;
		library.logger.info(<span class="hljs-string">"Orphaned block received"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">height</span>:block.height, <span class="hljs-attr">peer</span>:peer.string});
		<span class="hljs-keyword">return</span>;
	}

	<span class="hljs-keyword">if</span>(self.isForked(block)){
		__private.orphanedBlocks[block.id]=block;
		<span class="hljs-keyword">var</span> previousBlock = self.getPreviousBlock(block);
		library.logger.info(<span class="hljs-string">"Forked block received"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">height</span>:block.height, <span class="hljs-attr">previousBlock</span>: block.previousBlock, <span class="hljs-attr">previousBlockchainBlock</span>: previousBlock.id, <span class="hljs-attr">peer</span>:peer.string});
		<span class="hljs-keyword">return</span>;
	}

	<span class="hljs-keyword">if</span>(!self.isReady(block)){
		<span class="hljs-keyword">var</span> lastBlock = self.getLastBlock();
		library.logger.info(<span class="hljs-string">"Blockchain not ready to receive block"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">height</span>:block.height, <span class="hljs-attr">lastBlockHeight</span>: lastBlock.height, <span class="hljs-attr">peer</span>:peer.string});
		<span class="hljs-keyword">return</span>;
	}

	block.ready = <span class="hljs-literal">true</span>;

	<span class="hljs-keyword">return</span> self.addBlock(block);

};</pre></div></div>
            
        </li>
        
        
        <li id="section-52">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-52">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBlockForged</code></p>

            </div>
            
        </li>
        
        
        <li id="section-53">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-53">&#182;</a>
              </div>
              <p>Check if the forge block is coherent with current in-memory blockchain status
If so, marks block.ready = true and block.forged = true</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBlockForged = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block</span>) </span>{
	<span class="hljs-keyword">if</span>(self.isPresent(block)){
		modules.accounts.getAccount({<span class="hljs-attr">publicKey</span>:block.generatorPublicKey}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, delegate</span>)</span>{
			library.logger.error(<span class="hljs-string">"Double forgery - Same block - please disable delegate on one node"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">generator</span>:block.generatorPublicKey, <span class="hljs-attr">username</span>: delegate.username, <span class="hljs-attr">height</span>:block.height});
		});
		<span class="hljs-keyword">return</span>;
	}

	<span class="hljs-keyword">if</span>(self.isOrphaned(block)){
		modules.accounts.getAccount({<span class="hljs-attr">publicKey</span>:block.generatorPublicKey}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, delegate</span>)</span>{
			library.logger.error(<span class="hljs-string">"Double forgery - Orphaned block - please disable delegate on one node"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">generator</span>:block.generatorPublicKey, <span class="hljs-attr">username</span>: delegate.username, <span class="hljs-attr">height</span>:block.height});
		});
		<span class="hljs-keyword">return</span>;
	}

	<span class="hljs-keyword">if</span>(self.isForked(block)){
		<span class="hljs-keyword">var</span> previousBlock = self.getPreviousBlock(block);
		modules.accounts.getAccount({<span class="hljs-attr">publicKey</span>:block.generatorPublicKey}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, delegate</span>)</span>{
			library.logger.error(<span class="hljs-string">"Double forgery - Forked block - please disable delegate on one node"</span>, {<span class="hljs-attr">id</span>: block.id, <span class="hljs-attr">generator</span>:block.generatorPublicKey, <span class="hljs-attr">username</span>: delegate.username, <span class="hljs-attr">height</span>:block.height, <span class="hljs-attr">previousBlock</span>: block.previousBlock, <span class="hljs-attr">previousBlockchainBlock</span>: previousBlock.id});
		});
		<span class="hljs-keyword">return</span>;
	}

	block.ready = <span class="hljs-literal">true</span>;
	block.verified = <span class="hljs-literal">true</span>;
	block.forged = <span class="hljs-literal">true</span>;
  block.processed = <span class="hljs-literal">false</span>;
	block.broadcast = <span class="hljs-literal">true</span>;
	library.logger.info(<span class="hljs-string">"Adding forged to blockchain"</span>, block.id);
  self.addBlock(block);
}</pre></div></div>
            
        </li>
        
        
        <li id="section-54">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-54">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBlockVerified</code></p>

            </div>
            
        </li>
        
        
        <li id="section-55">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-55">&#182;</a>
              </div>
              <p>to update in-memory blockchain when block has been verified</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBlockVerified = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, cb</span>) </span>{
	<span class="hljs-keyword">var</span> error = <span class="hljs-literal">null</span>;
	<span class="hljs-keyword">if</span>(!__private.blockchain[block.height]){
		error = <span class="hljs-string">"Verified block not in blockchain. This is a bug, please do report"</span>;
	}
	<span class="hljs-keyword">else</span>{
		__private.blockchain[block.height].verified = <span class="hljs-literal">true</span>;
	}
}</pre></div></div>
            
        </li>
        
        
        <li id="section-56">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-56">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onBlockProcessed</code></p>

            </div>
            
        </li>
        
        
        <li id="section-57">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-57">&#182;</a>
              </div>
              <p>to update in-memory blockchain when block has been processed
and update lastBlock accordingly</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onBlockProcessed = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">block, cb</span>) </span>{

	<span class="hljs-keyword">var</span> error = <span class="hljs-literal">null</span>;
	<span class="hljs-keyword">if</span>(!__private.blockchain[block.height]){
		error = <span class="hljs-string">"Processed block not in blockchain. This is a bug, please do report"</span>;
	}
	<span class="hljs-keyword">else</span>{
		__private.blockchain[block.height].processed = <span class="hljs-literal">true</span>;
		__private.timestampState(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
		<span class="hljs-keyword">if</span>(__private.lastBlock &amp;&amp; __private.lastBlock.id == block.previousBlock){
			__private.lastBlock = block;
		}
		<span class="hljs-keyword">else</span>{
			error = <span class="hljs-string">"Processed block not consistent with last block on blockchain. This is a bug, please do report"</span>;
		}
	}
}</pre></div></div>
            
        </li>
        
        
        <li id="section-58">
          
            <div class="fullblock">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-58">&#182;</a>
              </div>
              <p><strong>EVENT</strong> <code>onFork</code></p>

            </div>
            
        </li>
        
        
        <li id="section-59">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-59">&#182;</a>
              </div>
              <p>Log the event in logs
TODO: no particular action taken yet</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>Blockchain.prototype.onFork = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">block, cause</span>) </span>{
	library.logger.info(<span class="hljs-string">'Fork'</span>, {
		<span class="hljs-attr">delegate</span>: block.generatorPublicKey,
		<span class="hljs-attr">block</span>: {
			<span class="hljs-attr">id</span>: block.id,
			<span class="hljs-attr">timestamp</span>: block.timestamp,
			<span class="hljs-attr">height</span>: block.height,
			<span class="hljs-attr">previousBlock</span>: block.previousBlock
		},
		<span class="hljs-attr">cause</span>: cause
	});

};</pre></div></div>
            
        </li>
        
        
        <li id="section-60">
          
            <div class="annotation">
          
              
              <div class="pilwrap ">
                <a class="pilcrow" href="#section-60">&#182;</a>
              </div>
              <p>manage the internal state logic</p>

            </div>
            
            <div class="content"><div class='highlight'><pre>__private.timestampState = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">lastReceipt</span>) </span>{
	<span class="hljs-keyword">if</span> (!__private.lastReceipt) {
		__private.lastReceipt = {
			<span class="hljs-attr">date</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
		};
	}
	<span class="hljs-keyword">if</span>(lastReceipt){
		__private.lastReceipt.date = lastReceipt;
	}

	<span class="hljs-keyword">var</span> timeNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime();
	__private.lastReceipt.secondsAgo = <span class="hljs-built_in">Math</span>.floor((timeNow -  __private.lastReceipt.date.getTime()) / <span class="hljs-number">1000</span>);
	<span class="hljs-keyword">if</span>(modules.delegates.isActiveDelegate()){
		__private.lastReceipt.stale = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">10</span>;
		__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">60</span>;
	}

	<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(modules.delegates.isForging()){
		__private.lastReceipt.stale = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">30</span>;
		__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">100</span>;
	}

	<span class="hljs-keyword">else</span> {
		__private.lastReceipt.stale = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">60</span>;
		__private.lastReceipt.rebuild = __private.lastReceipt.secondsAgo &gt; <span class="hljs-number">200</span>;
	}

	<span class="hljs-keyword">if</span>(__private.lastBlock.height &lt; <span class="hljs-number">52</span>){
		__private.lastReceipt.rebuild = <span class="hljs-literal">false</span>;
	}

	__private.lastReceipt.height = __private.lastBlock.height;

	<span class="hljs-keyword">return</span> __private.lastReceipt;
};


<span class="hljs-built_in">module</span>.exports = Blockchain;</pre></div></div>
            
        </li>
        
    </ul>
  </div>
</body>
</html>
